<?php

namespace App\Console\Commands;


use App\Adv;
use App\Jobs\Send;
use App\Lead;
use App\Notifications\JpushMsg;
use App\Notifications\JpushNotification;
use App\Project;
use App\ProjectUser;
use App\ToutiaoLead;
use App\User;
use App\UserProject;
use Carbon\Carbon;


use GuzzleHttp\Client;
use Illuminate\Console\Command;

class JinriCommand extends Command
{
    protected $key = [
        'zhongheng' => [
            'token' => 'abe755fa242957df6607d00f6a584b77d5306b95',
            'key' => 'TUFGNk9NR1dRT0U0',
            'project_id' => 3
        ],
        'huatengB' => [
            'token' => '78cf74ef13ae5febd7e2be9bc4c7580354a892f6',
            'key' => 'NUc3N0xEVTNER0pH',
            'project_id' => 6
        ],
        'huatengB2' => [
            'token' => 'b883f44d2245255df9eedd458acaf4497f0f1af4',
            'key' => 'SU82U1lRTkxSU1hY',
            'project_id' => 6
        ],
        'huatengB1' => [
            'token' => '5be4b0667a394ec974c15b7599b79d6e035b432b',
            'key' => 'N0hXRUtGNUQ0VURL',
            'project_id' => 6
        ],

        'huatengA' => [
            'token' => '3ad3640cdb9dd859ee25d1b072c6a3fbc54fb98d',
            'key' => 'RDhTNTZYVzZPTTc2',
            'project_id' => 5
        ],
        'huatengA1' => [
            'token' => '9f2c7d48e7bce13d8385e571ac16b52a86e35dc6',
            'key' => 'SzlPTkRYT1dUQTky',
            'project_id' => 5
        ],
        'huatengA2' => [
            'token' => 'e5c8a1aa04dc70f75eb0e9ac837663df824be89c',
            'key' => 'SlRRVEZJMUJISU00',
            'project_id' => 9,
        ],
        'weihe' => [
            'token' => 'bce15cfce979d374422fa788933937dda951bc35',
            'key' => 'SVlMTEZKVzhFRkdH',
            'project_id' => 9,
        ],
        'toutiao' => [
            'token' => '1a32fc1db23fa91f9f87a958d88d4d0cf77118e9',
            'key' => 'VlRZS1c2UjNWSkRY',
            'project_id' => 9,
        ]


    ];

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'jinri:project {project}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';
    protected $client;
    protected $customerRepository;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(Client $client)
    {
        $this->client = $client;
        parent::__construct();

    }


//头条获取数据接口

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $project = '';
        if (!isset($this->key[$this->argument('project')])) {
            $this->error('类型不对');

            return;
        };

        $config = $this->key[$this->argument('project')];
        $project_id = $config['project_id'];
        $project = Project::find($project_id);
        $host = "https://feiyu.oceanengine.com/";
        $api = "/crm/v2/openapi/pull-clues/";
        $date_s = Carbon::today()->toDateString();
        $date_e = Carbon::tomorrow()->toDateString();
        $now = time();
        $start_date = $date_s;
        $end_date = $date_e;
        $source_data = $api . '?start_time=' . $start_date . '&end_time=' . $end_date . ' ' . $now;
        $key = $config['key'];
        $tureOrFalse = true;
        $page = 1;
        while ($tureOrFalse) {

            $result = $this->client->get('https://feiyu.oceanengine.com/crm/v2/openapi/pull-clues/', [
                'headers' => [
                    'signature' => base64_encode(hash_hmac('sha256', $source_data, $key)),
                    'timestamp' => $now,
                    'Access-Token' => $config['token'],
                ],
                'query' => [
                    'start_time' => $start_date,
                    'end_time' => $end_date,
                    'page' => $page,
                    'page_size' => 100,
                ]
            ]);
            $page++;
            $app = json_decode($result->getBody()->getContents(), true);
            if (!empty($app['data'])) {
                foreach ($app['data'] as $v) {
                    $toutiao = ToutiaoLead::whereClueId($v['clue_id'])->first();
                    if ($toutiao) {
                        continue; //进入下次循环
                    }
                    if (!$toutiao) {
                        $v['token'] = $config['token'];
                        $v['key'] = $config['key'];
                        $toutiao = ToutiaoLead::create($v);
                        $this->info($toutiao->toJson());
                    }

                    //查询lead是否有
                    $lead = Lead::whereClueId($v['clue_id'])
                        ->first();
                    if (!$lead && !Lead::where('project_id', '=', $project_id)->where('mobile', '=', $toutiao->telphone)->first()) {
                        $lead = new Lead();
                        $lead->clue_id = $toutiao->clue_id;
                        $lead->customer_id = 0;
                        $lead->is_transform = 0;
                        $lead->name = $toutiao->name;
                        $lead->source = $toutiao->appname == '' ? '其他渠道' : $toutiao->appname;
                        $lead->detail_address = $toutiao->location . $toutiao->address;
                        $lead->remark = $toutiao->remark;

                        $moduleName = trim(preg_replace("/\\d+/", '', str_replace('电话', '', $toutiao->module_name)));

                        if (isset($config['owner_user_id'])) {
                            $owner_user_id = $config['owner_user_id'];
                        } elseif ($moduleName && User::where('realname', $moduleName)->first()) {
                            $user = User::where('realname', $moduleName)->first();
                            $owner_user_id = $user->id;
                            if ($project->type == 0) {
                                $userProject = UserProject::whereAdminUserId($user->id)->first();
                                $userProject->num = 1;
                                $userProject->save();
                            } elseif ($project->type == 1) {
                                $userProject = ProjectUser::whereUserId($user->id)->first();
                                $userProject->num = 1;
                                $userProject->save();
                            }
                        } elseif ($project->type == 0) {
                            $userProject = new  UserProject();
                            $owner_user_id = $userProject->current($project_id);
                        } elseif ($project->type == 1) {
                            $userProject = new ProjectUser();
                            $owner_user_id = $userProject->current($project_id);
                        } else {
                            $owner_user_id = 1;
                        }
                        //查询adv_id
                        $adv = Adv::whereAdvId($toutiao->adv_id)->first();
                        if ($adv) {
                            $create_user_id = $adv->user_id;
                        } else {
                            $create_user_id = 1;
                        }
                        $lead->create_user_id = $create_user_id;
                        $lead->mobile = $toutiao->telphone;
                        $lead->owner_user_id = $owner_user_id;
                        $lead->next_time = 0;
                        if (isset($v['remark_dict']['需求面积'])) {
                            $lead->crm_vfnlcv = $v['remark_dict']['需求面积'];
                        }
                        $lead->create_time = $toutiao->create_time;
                        $lead->status = '潜在客户';
                        $lead->project_id = $project_id;
                        $lead->update_time = $toutiao->create_time;
                        $lead->save();
                        if (config('app.env') === 'production') {
                            try {
                                if ($owner_user_id == 1) {
                                    dispatch(new Send($lead));
                                } else {
                                    $user = User::find($owner_user_id);
                                    if ($user) {
                                        $user->notify(new \App\Notifications\LeadsNotification($lead));
                                    }
                                }
                            } catch (\Exception $exception) {

                            }
                        }
                        \Log::info('新增线索', $lead->toArray());
                    }
                }

            } else {
                $tureOrFalse = false;
            }
        }
    }

}
